package com.huirui.server.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huirui.server.context.AdminContext;
import com.huirui.server.exception.AccountNotExistsException;
import com.huirui.server.exception.IncorrectPasswordException;
import com.huirui.server.mapper.AdminMapper;
import com.huirui.server.pojo.dto.AdminAddDto;
import com.huirui.server.pojo.dto.AdminLoginDto;
import com.huirui.server.pojo.entity.Admin;
import com.huirui.server.pojo.vo.AdminInfoVo;
import com.huirui.server.service.AdminService;
import com.huirui.server.util.IpUtils;
import com.huirui.server.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author yujun
 * @description 针对表【t_admin(管理员表)】的数据库操作Service实现
 * @createDate 2025-10-05 20:59:15
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public String login(AdminLoginDto adminLoginDto, HttpServletRequest request) {
        String account = adminLoginDto.getAccount();
        boolean exists = lambdaQuery()
                .eq(Admin::getAccount, account)
                .exists();
        if (!exists) {
            throw new AccountNotExistsException("账户不存在");
        }
        String password = adminLoginDto.getPassword();
        password = DigestUtil.md5Hex(password);
        Admin admin = lambdaQuery()
                .select(Admin::getId)
                .eq(Admin::getAccount, account)
                .eq(Admin::getPassword, password)
                .one();
        if (admin == null) {
            throw new IncorrectPasswordException("账号或密码不正确");
        }
        lambdaUpdate()
                .set(Admin::getLastLoginTime, LocalDateTime.now())
                .set(Admin::getLastLoginIp, IpUtils.getClientIp(request))
                .eq(Admin::getAccount, account)
                .update();

        return jwtUtil.createAdminToken(admin.getId());
    }

    @Override
    public void addEmployee(AdminAddDto adminAddDto) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminAddDto, admin);
        admin.setPassword(DigestUtil.md5Hex(admin.getPassword()));
        admin.setCreatedAt(LocalDateTime.now());
        admin.setUpdatedAt(LocalDateTime.now());
        save(admin);
    }

    @Override
    public AdminInfoVo getAdminInfo() {
        Long id = AdminContext.getId();
        Admin one = lambdaQuery()
                .select(Admin::getNickname)
                .eq(Admin::getId, id)
                .one();
        AdminInfoVo adminInfoVo = new AdminInfoVo();
        adminInfoVo.setId(Math.toIntExact(id));
        adminInfoVo.setNickname(one.getNickname());
        return adminInfoVo;
    }
}




